/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package doh.login;
import javax.ejb.*;
import javax.annotation.PreDestroy;
import doh.entity.Player;
import doh.service.ValidatorService;
import javax.annotation.PostConstruct;
import javax.persistence.EntityExistsException;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaBuilder;

/**
 *
 * @author lucas
 */
public class RegistrationService {

    @PersistenceContext
    private EntityManager em;
    private CriteriaBuilder cb;

    @PostConstruct
    private void init() {
        cb = em.getCriteriaBuilder();
    }

    public RegistrationService(EntityManager em, CriteriaBuilder cb){
        this.em = em;
        this.cb = cb;
        // insert admin user if he doesn't exist
        if(em.find(Player.class, "referee") == null){
            em.persist(new Player("referee", LoginService.getMD5("admin"), 1500, 0, 0, 1.00, 0.00, 0, 0, 0));
        }
    }

//    public boolean registerAs(String user, String password){
//        return this.register(user, password);
//    }

    public boolean register(String id, String password){
        if(ValidatorService.isValidInput(id) && ValidatorService.isValidInput(password)){
            if(em.find(Player.class, id) != null){
                return false;
            }
            String hpasswd = LoginService.getMD5(password);
            Player p = new Player(id, hpasswd, 1500, 0, 0, 1.00, 0.00, 0, 0, 0);
            try {
                em.persist(p);
            } catch (Exception e){
                // entity already exists, don't create
                e.printStackTrace();
                return true;
            }
            return true;
        }
        return false;
    }

    public boolean deleteUser(String id)
    {
        Player p;
        if(ValidatorService.isValidInput(id)){
            if((p = em.find(Player.class, id)) != null){
                em.remove(p);
                return true;
            }
        }
        return false;
    }

    public boolean changePassword(String id, String password)
    {
        Player p;
        if(ValidatorService.isValidInput(id) && ValidatorService.isValidInput(password)) {
            String hpasswd = LoginService.getMD5(password);
            if ((p = em.find(Player.class, id)) != null) {
                p.set_password(hpasswd);
                em.persist(p);
                return true;
            }
        }
        return false;
    }

    @PreDestroy
    private void tearDown(){
        em.close();
    }
}
